package com.ruoyi.quartz.task;

import com.ruoyi.alarmmanagement.job.*;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.datastatistics.service.ICopyRateService;
import com.ruoyi.datastatistics.service.IHourUsageDbService;
import com.ruoyi.datastatistics.service.ITerminalsFreezeXbService;
import com.ruoyi.datastatistics.service.RecvDataService;
import com.ruoyi.quartz.service.IGeneratetDataXbService;
import com.ruoyi.quartz.service.IRunWarnsService;
import com.ruoyi.quartz.service.IRunXbWarnsService;
import com.ruoyi.quartz.service.ISynDeviceIdService;
import com.ruoyi.quartz.util.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.time.LocalDate;
import java.time.YearMonth;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

/**
 * 定时任务调度测试
 *
 * @author ruoyi
 */
@Slf4j
@Component("ryTask")
public class RyTask {

    @Autowired
    private IRunWarnsService runWarnsService;

    @Autowired
    private IRunXbWarnsService runXbWarnsService;

    @Autowired
    private ISynDeviceIdService synDeviceIdService;

    @Autowired
    private IGeneratetDataXbService generatetDataXbService;


    @Autowired
    private ICopyRateService copyRateService;

    @Autowired
    private IHourUsageDbService hourUsageDbService;
    @Autowired
    private ITerminalsFreezeXbService terminalsFreezeXbService;
    @Autowired
    private RecvDataService recvDataService;


    public void ryMultipleParams(String s, Boolean b, Long l, Double d, Integer i) {
        System.out.println(StringUtils.format("执行多参方法： 字符串类型{}，布尔类型{}，长整型{}，浮点型{}，整形{}", s, b, l, d, i));
    }

    public void ryParams(String params) {
        System.out.println("执行有参方法：" + params);
    }

    public void ryNoParams() {
        System.out.println("执行无参方法");
    }

    public void ryWarns() throws ParseException {
        String date = DateUtil.getStringDate("yyyy-MM-dd");
        runWarnsService.job_InstantFlowMutationWarning(date);
        runWarnsService.job_PressMutationWarning(date);
        runWarnsService.job_FreezeDay();

    }

    public void ryXbWarns() {
        runXbWarnsService.job_Ultralimit();
    }

    public void synDeviceId() {
        synDeviceIdService.job_synchronizationDeviceId();
    }


    // 定时生成日冻结数据
    public void GeneratetDayFreezeXb() {
        generatetDataXbService.GeneratetDayFreeze();
    }

    public void GeneratetMonthFreezeXb() {
        generatetDataXbService.GeneratetMonthFreeze();
    }

    public void genCopyData(String date, Integer terminalType) {
        if (StringUtils.isBlank(date)) {
            LocalDate localDate = LocalDate.now().minusDays(1);
            date = localDate.toString();
        }
        copyRateService.addCopyDataByDate(date, terminalType);
    }

    public void genHourUsageDb(String beginDate, String endDate) {
        if (StringUtils.isBlank(beginDate)) {
            LocalDate date = LocalDate.now().minusDays(1);
            beginDate = date.toString();
        }
        if (StringUtils.isBlank(endDate)) {
            LocalDate date = LocalDate.now().minusDays(1);
            endDate = date.toString();
        }
        hourUsageDbService.addHourUsage(beginDate, endDate);
    }

    public void genWarnData(String dateStr) {
        Date date;
        if (StringUtils.isBlank(dateStr)) {
            date = DateUtils.toDate(LocalDate.now().minusDays(1));
        } else {
            date = DateUtils.parseDate(dateStr);
        }
        Set<Class<? extends BaseWarnJob>> classList = BaseWarnJob.getSubClasses();
        List<CompletableFuture<String>> futures = new ArrayList<>(classList.size());
        for (Class<? extends BaseWarnJob> clazz : classList) {
            CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
                SpringUtils.getBean(clazz).execute(date);
                return String.format("执行预警生成任务：%s成功", clazz.getName());
            }).exceptionally(ex -> {
                log.error("执行预警生成任务：{}出错", clazz.getName(), ex);
                return null;
            });
            futures.add(future);
        }
        CompletableFuture<Void> allOf = CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]));
        CompletableFuture<List<String>> allResults = allOf.thenApply(v ->
                futures.stream()
                        .map(CompletableFuture::join)
                        .filter(Objects::nonNull)
                        .collect(Collectors.toList())
        );

        // 获取并打印所有结果
        try {
            List<String> results = allResults.get();
            log.info(results.toString());
        } catch (Exception ignored) {
        }
    }

    public void genTerminalFreezeXb(String dateStr) {
        terminalsFreezeXbService.generateFreezeDataXb(dateStr);
    }

    public void genTerminalMonthlyFreezeXb() {
        YearMonth yearMonth = YearMonth.now().minusMonths(1);
        terminalsFreezeXbService.generateFreezeDataXb(yearMonth.toString());
    }

    /**
     * 定时从中间库同步户表历史数据
     */
    public void syncXbDataFromIntermediateDatabase() {
        recvDataService.saveHistoryDataXb();
    }

    /**
     * 定时从中间库同步大表历史数据
     */
    public void syncDbDataFromIntermediateDatabase() {
        recvDataService.saveHistoryDataDb();
    }

    /**
     * 定时清理中间库数据
     */
    public void deleteRecvDataRegularly(){
        recvDataService.deleteRecvDataRegularly();
    }
}
